package com.soup.lab.spring.retry.service.usecase;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

@Component
public class RetryableThirdInvoker implements ThirdInvoker {

    private static final Logger logger = LoggerFactory.getLogger(RetryableThirdInvoker.class);

    @Override
    @Retryable(
            include = IOException.class,
            listeners = "invokeRetryListener",
            backoff = @Backoff(value = 2000L, multiplier = 2, maxDelay = 30000L))
    public InvokeRes invoke(InvokeReq req) throws IOException {
        URL url = new URL(req.getReqAddr());
        URLConnection urlConnection = url.openConnection();
        try(BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                logger.info(line);
            }
        }
        return new InvokeRes("200");
    }

    @Recover
    public InvokeRes recover() {
        return new InvokeRes("500");
    }

}
